<?php
/**
 * Created by PhpStorm.
 * User: tengwei
 * Date: 2018/11/22
 * Time: 9:49 AM
 */
namespace common\logics\config;

use common\widgets\Request;
use common\widgets\Tool;
use phpDocumentor\Reflection\Types\Self_;
use yii\base\BaseObject;
use Yii;

class ConfigLogic extends BaseObject implements IConfig
{
    public static $error_local;
    const CHECK_FILE_NAME = '请检查文件名称是否正确';
    const CHECK_FILE_TYPE = '请检查文件类型是否正确';
    const FAIL_FILE_MOVE = '文件转移失败';

    /** @var \common\sources\write\config\ConfigAccess $WConfigAccess */
    private $WConfigAccess;
    /** @var \common\sources\read\config\ConfigAccess $RConfigAccess */
    private $RConfigAccess;
    /** @var \common\sources\read\sendddcode\SendDdCodeAccess $RSendDdCodeAccess **/
    private $RSendDdCodeAccess;
    /** @var \common\sources\write\sendddcode\SendDdCodeAccess $WSendDdCodeAccess **/
    private $WSendDdCodeAccess;
    /** @var \common\sources\write\systemconfig\SystemConfigAccess $WSystemConfigAccess */
    private $WSystemConfigAccess;
    /** @var \common\sources\read\systemconfig\SystemConfigAccess $RSystemConfigAccess */
    private $RSystemConfigAccess;

    public function init()
    {
        $this->WConfigAccess = Yii::$container->get("WConfigAccess");
        $this->RConfigAccess = Yii::$container->get("RConfigAccess");
        $this->RSendDdCodeAccess = Yii::$container->get("RSendDdCodeAccess");
        $this->WSendDdCodeAccess = Yii::$container->get("WSendDdCodeAccess");
        $this->WSystemConfigAccess = Yii::$container->get('WSystemConfigAccess');
        $this->RSystemConfigAccess = Yii::$container->get('RSystemConfigAccess');
        parent::init(); // TODO: Change the autogenerated stub
    }

    public function ChangePayType($data) {
        if(empty($data['company']))
        {
            return Tool::returnJson([],401,"公司不能为空");
        }
        if(empty($data['qk_config_rmb']))
        {
            return Tool::returnJson([],401,"人民币网关账号不能为空");
        }
        if(empty($data['bgUrl']))
        {
            return Tool::returnJson([],401,"接收支付结果的后台地址不能为空");
        }
        if(empty($data['productName']))
        {
            return Tool::returnJson([],401,"商品名不能为空");
        }
        if(empty($data['payType']))
        {
            return Tool::returnJson([],401,"支付方式不能为空");
        }

        //增加钉钉验证码=验证
        if(empty($data['sys_code'])){
            return Tool::returnJson([],401,"请填写验证码");
        }
        if(empty($data['uid'])){
            return Tool::returnJson([],401,"操作人不能为空");
        }
        $smsArr = $this->RSendDdCodeAccess->getSendDdCode($data);
        if (intval($smsArr['code']) !== intval($data['sys_code'])) {
            return Tool::returnJson($data = [], $code = 405, '验证码输入有误');
        }
        $this->WSendDdCodeAccess->delDdCodeById($smsArr['id']);        //删除钉钉验证码

        # 文件上传转移
        $upload = Self::fileUpload();
        if (! $upload) {
            return Tool::returnJson([],409,static::CHECK_FILE_TYPE);
        }
        $data['cert_path'] = $upload['cert_path'];
        $data['pem_path'] = $upload['pem_path'];
        $result = $this->WConfigAccess->ChangePayType($data);
        if ($result) {
            return Tool::returnJson([],200,'成功');
        }
        return Tool::returnJson([],200,'失败');
    }

    public static function fileUpload() {
        $data = [];
        $files = $_FILES;
        foreach ($files as $key => $file) {
            if ($file['size'] == 0) {
                unset($files[$key]);
            }
            if (!is_dir("../common/services/kq/qiyun/")) {
                mkdir("../common/services/kq/qiyun/",true);
            }
            $upload = copy($file['tmp_name'],"../common/services/kq/qiyun/".$file['name']);
            if (!$upload) {
                static::$error_local = static::FAIL_FILE_MOVE;
                return false;
            }
            $data[$key] = "../common/services/kq/qiyun/".$file['name'];
        }
        return $data;
    }

    public function GetList() {
        $result = $this->RConfigAccess->GetList();
        return Tool::returnJson($result,200,'成功');
    }

    public function UsePayConfig($data) {
        if (empty($data['id'])) {
            return Tool::returnJson([],401,'id不能为空');
        }
        //增加钉钉验证码=验证
        if(empty($data['sys_code'])){
            return Tool::returnJson([],401,"请填写验证码");
        }
        if(empty($data['uid'])){
            return Tool::returnJson([],401,"操作人不能为空");
        }
        $smsArr = $this->RSendDdCodeAccess->getSendDdCode($data);
        if (intval($smsArr['code']) !== intval($data['sys_code'])) {
            return Tool::returnJson($data = [], $code = 405, '验证码输入有误');
        }
        $this->WSendDdCodeAccess->delDdCodeById($smsArr['id']);        //删除钉钉验证码

        $result = $this->WConfigAccess->UsePayConfig($data);
        if ($result) {
            return Tool::returnJson([],200,'成功');
        }
        return Tool::returnJson([],409,'失败');
    }

    public function DelPayConfig($data) {
        if (empty($data['id'])) {
            return Tool::returnJson([],401,'id不能为空');
        }
        //增加钉钉验证码=验证
        if(empty($data['sys_code'])){
            return Tool::returnJson([],401,"请填写验证码");
        }
        if(empty($data['uid'])){
            return Tool::returnJson([],401,"操作人不能为空");
        }
        $smsArr = $this->RSendDdCodeAccess->getSendDdCode($data);
        if (intval($smsArr['code']) !== intval($data['sys_code'])) {
            return Tool::returnJson($data = [], $code = 405, '验证码输入有误');
        }
        $this->WSendDdCodeAccess->delDdCodeById($smsArr['id']);        //删除钉钉验证码

        $result = $this->WConfigAccess->DelPayConfig($data);
        if ($result) {
            return Tool::returnJson([],200,'成功');
        }
        return Tool::returnJson([],409,'失败');
    }

    public function GetPayConfig() {
        $result = $this->RConfigAccess->GetPayConfig();
        if ($result) {
            return $result;
        }
        return [];
    }

    //发送钉钉消息
    public function sendDD($data)
    {
        if(empty($data['operator']))
        {
            return Tool::returnJson([],406,"操作人不能为空");
        }
        $ramd = rand(100000,999999);
        $webhook = Yii::$app->params['sms_ddcode__url'];
        $message="日期：【".date("Y-m-d H:i:s",time())."】
描述:【管理员".$data['operator']. "正在进行" . $data['content'] . "操作】
验证码：【".$ramd."】";
        $param = array ('msgtype' => 'text','text' => array ('content' => $message),"at"=>["isAtAll" =>true]);
        $data_string = json_encode($param);
        $result = $this->request_by_curl($webhook, $data_string);
        $arr = json_decode($result,true);
        if($arr['errcode'] == 0)
        {
            //增加验证码记录
            $codeArr = [
                "uid" => $data['uid'],
                "code" => $ramd,
                "status" => 1,
                "operator" => $data['operator'],
            ];
            $this->WSendDdCodeAccess->sendDdCode_1($codeArr);
            return Tool::returnJson([],200,"发生钉钉成功");
        }else{
            return Tool::returnJson([],408,"发送钉钉失败");
        }
    }

    //第三方退款账户切换
    public function CheckRefundType($data) {
        if (empty($data['ConfigName'])) {
            return Tool::returnJson([],401,"配置名称不能为空");
        }
        if (empty($data['ConfigValue'])) {
            return Tool::returnJson([],401,"配置值不能为空");
        }
        $result = $this->WSystemConfigAccess->CheckRefundType($data);
        if ($result) {
            return Tool::returnJson([],200,'成功');
        }
        return Tool::returnJson([],409,'失败');
    }

    private function request_by_curl($remote_server, $post_string)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $remote_server);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array ('Content-Type: application/json;charset=utf-8'));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // 线下环境不用开启curl证书验证, 未调通情况可尝试添加该代码
        curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $data = curl_exec($ch);
        curl_close($ch);

        return $data;
    }
}